package cn.feizhu.aimarket.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.feizhu.aimarket.common.BaseResponse;
import cn.feizhu.aimarket.common.ResultUtils;
import jakarta.annotation.Resource;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/monitor/rate-limit")
public class RateLimitMonitorController {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 查看当天各限流Key的违例次数（仅管理员）
     */
    @SaCheckLogin
    @SaCheckRole("admin")
    @GetMapping("/violations/today")
    public BaseResponse<Map<String, Long>> listTodayViolations() {
        RMapCache<String, Long> violations = redissonClient.getMapCache("rate_limit:violations");
        String suffix = ":" + LocalDate.now();
        Map<String, Long> today = new HashMap<>();
        for (String k : violations.keySet()) {
            if (k.endsWith(suffix)) {
                Long v = violations.get(k);
                if (v != null) {
                    today.put(k, v);
                }
            }
        }
        return ResultUtils.success(today);
    }
}